package core

import (
	"context"
	"fmt"
	"time"

	"github.com/go-redis/redis/v8"
)

var RedisClient *redis.Client
var ctx = context.Background()

func init() {
	RedisClient = redis.NewClient(&redis.Options{
		Addr:     Config.Application.Redis.Addr,     // Redis服务器地址
		Password: Config.Application.Redis.Password, // 无密码
		DB:       Config.Application.Redis.DB,       // 默认DB
	})

	_, err := RedisClient.Ping(ctx).Result()
	if err != nil {
		fmt.Printf("Failed to connect to Redis: %v\n", err)
	}
}

func SetRedisKey(key string, value interface{}, expiration time.Duration) error {
	return RedisClient.Set(ctx, key, value, expiration).Err()
}

func GetRedisKey(key string) (string, error) {
	return RedisClient.Get(ctx, key).Result()
}

func DelRedisKey(key string) error {
	return RedisClient.Del(ctx, key).Err()
}

func ExistsRedisKey(key string) bool {
	result, _ := RedisClient.Exists(ctx, key).Result()
	return result > 0
}
